<?php

namespace App\Http\Controllers\Admin;

use App\Models\Classes;
use App\Models\ClassLessonTeacher;
use App\Models\Lesson;
use App\Models\Teacher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

/**
 * 课程表管理
 * Class TypeController
 * @package App\Http\Controllers\Admin
 */
class ClassLessonTeacherController extends BaseController
{
    /**
     * 分类列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $types = [
            '01' => '初一',
            '02' => '初二',
            '03' => '初三',
            '04' => '高一',
            '05' => '高二',
            '06' => '高三',
        ];
        $years = $lessons = []; $nowYear = date('Y');
        //已经存在的课程表年度学期
        $list = ClassLessonTeacher::select('year')->distinct()->orderBy('year')->get();
        foreach ($list as $item) {
            $y = substr($item->year, 0, 4);
            $x = substr($item->year, 4, 2);
            $years[$item->year] = $y.'年 第'.($x=='01'?'一':'二').'学期';
        }
        //增加本年度学期
        if (!isset($years[$nowYear.'01'])) {
            $years[$nowYear.'01'] = $nowYear.'年 第一学期';
        }
        if (!isset($years[$nowYear.'02'])) {
            $years[$nowYear.'02'] = $nowYear.'年 第二学期';
        }

        $query = $request->only(['year', 'type']);
        if (!empty($query['type']) && !empty($query['year'])) {
            //查询课表
            $res = ClassLessonTeacher::where('year', $query['year'])
                ->where('c_code', 'like', $query['type'].'%')
                ->orderBy('week')
                ->orderBy('c_code')
                ->orderBy('sort')
                ->get();
            $lessons = $this->dataHandle($res, $query);
        }
        $weeks = ClassLessonTeacher::$week;
        return backendView('classlessonteacher.index', compact('years', 'types', 'lessons', 'query','weeks'));
    }

    /**
     * 课表数据处理
     * @param $data
     * @return array 学期年级完整的课表
     */
    public function dataHandle($data, $query)
    {
        $out = []; $w = 1; $s = 0; $temp = [];
        if (!empty($data)) {
            //查询结果处理 星期-班级-完整的八节课早晚自习
            foreach ($data as $item) {
                $temp[$item->week][$item->c_code][$item->sort] = $item;
            }
            $class = Classes::where('c_code', 'like', $query['type'].'%')->get();
            //处理完整的星期
            foreach (ClassLessonTeacher::$week as $i=>$weekItem) {
                //班级
                foreach ($class as $classItem) {
                    //八节课早晚自习
                    foreach (ClassLessonTeacher::$sort as $j=>$sortItem) {
                        if (!empty($temp[$i][$classItem->c_code][$j])) {
                            $out[$i][$classItem->c_code][$j] = ['lesson'=>$temp[$i][$classItem->c_code][$j]->lesson->name, 'teacher'=>$temp[$i][$classItem->c_code][$j]->teacher->name];
                        } else {
                            $out[$i][$classItem->c_code][$j] = ['lesson'=>'', 'teacher'=>''];
                        }
                    }
                }
            }
        }
        return $out;
    }

    /**
     * 新增分类
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function add(Request $request)
    {
        $query = $request->only(['year','week','class','sort','l_code','tc_code']);
        $h = [];
        //是否存在课程(编辑)
        $h = ClassLessonTeacher::where('year',$query['year'])
            ->where('c_code',$query['class'])
            ->where('week',$query['week'])
            ->where('sort',$query['sort'])
            ->first();
        if (!empty($query['l_code']) && !empty($query['tc_code'])) {
            if (empty($h)) {
                $data = [
                    'l_code' => $query['l_code'],
                    'tc_code' => $query['tc_code'],
                    'c_code' => $query['class'],
                    'year' => $query['year'],
                    'week' => $query['week'],
                    'sort' => $query['sort'],
                ];
                if (ClassLessonTeacher::create($data)) {
                    return redirect()->route('admin.classLessonTeacher.index', ['year' => $query['year'], 'type' => substr($query['class'], 0, 2)])->with('success', __('Create success'));
                }
                return back()->with('error', __('Create failed'))->withInput();
            } else {
                $data = [
                    'l_code' => $query['l_code'],
                    'tc_code' => $query['tc_code'],
                ];
                if ($h->update($data)) {
                    return redirect()->route('admin.classLessonTeacher.index', ['year' => $query['year'], 'type' => substr($query['class'], 0, 2)])->with('success', __('Edit success'));
                }
                return back()->with('error', __('Edit failed'))->withInput();
            }
        } else {
            //所有课程
            $lessons = Lesson::all();
            //所有任课教师
            $teachers = Teacher::where('is_logistics', 0)->get();
            //本学年本学期 教课组合
            $res = ClassLessonTeacher::select('l_code','tc_code')->distinct()
                ->where('year',$query['year'])
                ->where('c_code', 'like', substr($query['class'],0,2).'%')
                ->orderBy('l_code')
                ->get();
            $possible = []; $tmp = '';
            //处理数据结构
            foreach($res as $item) {
                if($tmp != $item->lesson->name) {
                    $tmp = $item->lesson->name;
                }
                $possible[$tmp][] = $item;
            }
            $weeks = ClassLessonTeacher::$week;
            return backendView('classlessonteacher.add', compact('lessons','teachers','possible','query','weeks','h'));
        }
    }

    public function delete($id = null)
    {

        $res = ClassLessonTeacher::find($id);
        if (empty($res)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        try {
            if ($res->delete()) {
                return redirect()->route('admin.classLessonTeacher.index', ['year' => $res['year'], 'type' => substr($res['c_code'], 0, 2)])->with('success', __('Delete success'));
            }
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('error', __('Delete failed'));
    }
}